package com.hj.api;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;

import com.google.gson.Gson;
import com.hj.api.bean.*;
import com.hj.api.constant.URL;
import com.hj.api.util.HttpUtils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.hj.api.constant.URL.weChatRz;
import static com.hj.api.util.Constant.developerId;
import static com.hj.api.util.Constant.developerKey;

@RestController
@RequestMapping("v1.0")
public class APIController {

    String version = "1.0";
    String logTypes[] = new String[]{"0","1","3"};

    String keys[] = new String[]{"token","acode","appId","jh","name","department","position"
            ,"mobile","gender","email","avatar"};
    String vals[] = new String[]{"凭证","微信acode","应用id","警号（身份证）","姓名","所属部门","职位"
            ,"手机号码","性别","邮箱","头像URL"
    };



    @Autowired
    private RestTemplate restTemplate ;


    @RequestMapping("getDicByType")
    public  String getDicByType(HttpServletRequest request){

        return restTemplate.postForObject(URL.getDicByType, HttpUtils.getPara(request), String.class);
    }
    @RequestMapping("assetData")
    public  String assetData(HttpServletRequest request){

        return restTemplate.postForObject(URL.assetData, HttpUtils.getPara(request), String.class);
    }
    @RequestMapping("submitDealData")
    public  String submitDealData(HttpServletRequest request){

        return restTemplate.postForObject(URL.submitDealData, HttpUtils.getPara(request), String.class);
    }
    @RequestMapping("addAsset")
    public  String addAsset(HttpServletRequest request){

        return restTemplate.postForObject(URL.addAsset, HttpUtils.getPara(request), String.class);
    }
    @RequestMapping("pdData")
    public  String pdData(HttpServletRequest request){

        return restTemplate.postForObject(URL.pdData, HttpUtils.getPara(request), String.class);
    }

    @RequestMapping("getPDDetails")
    public  String getPDDetails(HttpServletRequest request){

        return restTemplate.postForObject(URL.getPDDetails, HttpUtils.getPara(request), String.class);
    }



    @RequestMapping("PDDetailsSaveResult")
    public  String PDDetailsSaveResult(HttpServletRequest request){

        return restTemplate.postForObject(URL.PDDetailsSaveResult, HttpUtils.getPara(request), String.class);
    }

    @RequestMapping("submitChangeData")
    public  String submitChangeData(HttpServletRequest request){

        return restTemplate.postForObject(URL.submitChangeData, HttpUtils.getPara(request), String.class);
    }
    @RequestMapping("submitAllocData")
    public  String submitAllocData(HttpServletRequest request){

        return restTemplate.postForObject(URL.submitAllocData, HttpUtils.getPara(request), String.class);
    }
    @RequestMapping("submitDisposalData")
    public  String submitDisposalData(HttpServletRequest request){

        return restTemplate.postForObject(URL.submitDisposalData, HttpUtils.getPara(request), String.class);
    }

    @RequestMapping("indexTest")
    public  String indexTest(HttpServletRequest request){

        return "转发服务运行正常";
    }


    @RequestMapping("getToken")
    public  String getToken(HttpServletRequest request,String developerId,String developerKey){

        TokenBean data = restTemplate.getForObject(URL.getToken, TokenBean.class);
        TimedTask.setTokenBean(data);
        System.out.println("developerId ->"+developerId);
        return "更新token成功";
    }
    @PostConstruct
    public void initToken() {

        try {
            Gson gson = new Gson();
            HashMap<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("developerId", developerId);
            paramMap.put("developerKey", developerKey);
            String result3 = HttpUtil.get(URL.getToken, paramMap);
            TokenBean data = gson.fromJson(result3, TokenBean.class);
            TimedTask.setTokenBean(data);
            String res = HttpRequest.post(URL.sq)
                    .header("Content-type", "application/json")
                    .body(gson.toJson(TimedTask.sqPostBean))
                    .execute()
                    .body();
            ;
            SQDataBean sqDataBean = gson.fromJson(res, SQDataBean.class);
            TimedTask.setSqDataBean(sqDataBean);
            System.out.println("日志token 返回"+res);
            System.out.println("数广token 返回"+result3);
        } catch (Exception e) {
            e.printStackTrace();
        }



    }

    @RequestMapping("login")
    public  String login(HttpServletRequest request){
        System.out.println("进入鉴权");
        String pra = request.getParameter("data");
        System.out.println("api login->" + pra);
        Gson gson = new Gson();
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        String sid = "17";
        paramMap.put("token", TimedTask.getTokenBean().getData().getToken());
        paramMap.put("acode", pra);
        paramMap.put("appId", "0000021");
        String mapStr = gson.toJson(paramMap);
        System.out.println("请求参数："+mapStr);
        String result3= HttpUtil.get(URL.login, paramMap);
        System.out.println("请求返回-->"+result3);
        BaseBean baseBean = gson.fromJson(result3, TXLoginData.class);
        if ("1003".equals(baseBean.getCode())) {
            sid = "18";
            paramMap.put("appId", "0000009");
            mapStr = gson.toJson(paramMap);
            System.out.println("请求参数："+mapStr);
            result3= HttpUtil.get(URL.login, paramMap);
            try {
                System.out.println("开始请求发送日志");
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("sid", sid);
                map.put("data", result3);
                map.put("type", getByRandom(0));
                HttpUtil.get("http://10.40.114.254:6789/api/v1.0/tjrz", map);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("发送日志出错");
            }
        }
        System.out.println("api login ->" + result3);


        return result3;
    }


    @RequestMapping("getDeptByDeptId")
    public  String getDeptByDeptId(HttpServletRequest request){

        String departId = request.getParameter("departId");
        Gson gson = new Gson();
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("token", TimedTask.getTokenBean().getData().getToken());
        if (StringUtils.isNotEmpty(departId)) {
            paramMap.put("departId", departId);
        }
        paramMap.put("appId", "0000021");
        String mapStr = gson.toJson(paramMap);
        System.out.println("请求参数："+mapStr);
        String result3= HttpUtil.get(URL.getDeptByDeptId, paramMap);
        System.out.println("api getDeptByDeptId ->" + result3);
        return result3;
    }
    @RequestMapping("getUserByDepartId")
    public  String getUserByDepartId(HttpServletRequest request){

        String departId = request.getParameter("departId");
        Gson gson = new Gson();
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("token", TimedTask.getTokenBean().getData().getToken());
        paramMap.put("departId", departId);
        paramMap.put("appId", "0000021");
        String mapStr = gson.toJson(paramMap);
        System.out.println("请求参数："+mapStr);
        String result3= HttpUtil.get(URL.getUserByDepartId, paramMap);
        System.out.println("api getDeptByDeptId ->" + result3);
        return result3;
    }

    @RequestMapping("toUrl")
    public  String toUrl(HttpServletRequest request,String url){

        return HttpUtil.get(url);
    }


    @RequestMapping("fsUser")
    public  String fsUser(){
        return HttpUtil.get("http://10.45.131.63:8080/servlet/org?type=user");
    }
    @RequestMapping("fsDep")
    public  String fsDep(){

        return HttpUtil.get("http://10.45.131.63:8080/servlet/org?type=dep");
    }


    public String getByRandom(int i) {

        String data = "";
        switch (i) {
            case 0:
                int index = (int) (Math.random() * logTypes.length);
                data = logTypes[index];
        }
        return data;
    }

    @RequestMapping("rz")
    @ResponseBody
    public String rz(HttpServletRequest request, String url) {

        Gson gson = new Gson();
        Map<String, String> param = new HashMap<String, String>();
        param.put("policeId", "003222");
        param.put("sn", "003222");
        param.put("cardNo", "44092119900315777X");
        param.put("source", "18"); // 通过系统应用注册获得
        param.put("logType", getByRandom(0));
        param.put("params", "name=1,password=1");
        param.put("url", "http://10.40.114.254:6789/api/v1.0/");
        param.put("uri", "/api/v1.0/");
        param.put("response", "[{\"性别\":\"男\",\"姓名\":\"测试1\"},{\"性别\":\"男\",\"姓名\":\"测试2\"}]");
        param.put("responseType", "1");
        param.put("result", "成功");
        param.put("sourceIp", "11.12.110.254");
        param.put("sourcePort", "16789");
        param.put("destIp", "10.40.114.254");
        param.put("destPort", "6789");
        param.put("terminalIp", "");
        param.put("module", "");
        param.put("formatParam", "{\"身份证号\":\"44092119900315777X\",\"姓名\":\"测试1\"}");
        param.put("content", "/api/" + System.currentTimeMillis());
        param.put("errorLog", "");
        param.put("responseTime", (50 + (int) (Math.random() * 50)) + "");
        param.put("time", System.currentTimeMillis() + "");

        List<Object> l1 = new ArrayList<Object>();
        l1.add(param);
        String p1 = gson.toJson(l1);
        String result1 = HttpRequest.post(weChatRz)
                .header("token", TimedTask.getSqDataBean().result)
                .header("Content-type", "application/json")
                .body(p1)
                .execute()
                .body();

        param.put("time", (System.currentTimeMillis() + 1000) + "");
        param.put("logType", getByRandom(0));
        param.put("source", "17");
        param.put("responseTime", (50 + (int) (Math.random() * 50)) + "");
        List<Object> l2 = new ArrayList<Object>();
        l2.add(param);
        String p2 = gson.toJson(l2);
        String result2 = HttpRequest.post(weChatRz)
                .header("token", TimedTask.getSqDataBean().result)
                .header("Content-type", "application/json")
                .body(p2)
                .execute()
                .body();

        System.out.println("result1 返回" + result1);
        System.out.println("result2 返回" + result2);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("result1",result1);
        map.put("result2",result2);
        map.put("p1",p1);
        map.put("p2",p2);
        map.put("token",TimedTask.getSqDataBean().result);

        return gson.toJson(map);
    }

    @RequestMapping("apiTest")
    @ResponseBody
    public String apiTest() {

        return "api success version"+version;

    }

    public String forMat(String str) {

        for (int i = 0; i < keys.length; i++) {
            String key = keys[i];
            String val = vals[i];
            str = str.replaceAll(key,val);
        }
        return str;
    };

    @RequestMapping("tjrz")
    @ResponseBody
    public String tjrz(String sid,String data,String type) {
        Gson gson = new Gson();
        System.out.println("日志请求data----->"+data);
        System.out.println("日志请求sid----->"+sid);
        System.out.println("日志请求type----->"+type);
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("token", TimedTask.getTokenBean().getData().getToken());
        paramMap.put("acode", System.currentTimeMillis()+"");
        if ("17".equals(sid)) {
            paramMap.put("appId", "0000021");
        }
        else if ("18".equals(sid)) {
            paramMap.put("appId", "0000009");
        }else{
            paramMap.put("appId", "0000021");
        }
        String mapStr = gson.toJson(paramMap);
        TXLoginData txLoginData = null;
        txLoginData = gson.fromJson(data, TXLoginData.class);
        List<TXLogin> logins = new ArrayList<TXLogin>();
        logins.add(txLoginData.getData());
        if (StringUtils.isBlank(type)) {
            type = getByRandom(0);
        }
        String formatParam = forMat(mapStr);
        String resultStr = forMat(gson.toJson(logins));
        Map<String, String> param = new HashMap<String,String>();
        param.put("policeId", txLoginData.getData().getExtJh()==null? "":txLoginData.getData().getExtJh());
        param.put("sn", txLoginData.getData().getExtJh()== null ? "":txLoginData.getData().getExtJh());
        param.put("cardNo", txLoginData.getData().getJh() == null? "": txLoginData.getData().getJh());
        param.put("source", sid);
        param.put("logType", type);
        param.put("params", mapStr);
        param.put("url", "http://10.40.114.254:6789/api/v1.0/");
        param.put("uri", "/api/v1.0/");
        param.put("response", resultStr);
        param.put("responseType", "1");
        param.put("result", "成功");
        param.put("sourceIp", "11.12.110.254");
        param.put("sourcePort", "16789");
        param.put("destIp", "10.40.114.254");
        param.put("destPort", "6789");
        param.put("terminalIp", "10.40.114.254");
        param.put("module", "系统管理->登录");
        param.put("formatParam", formatParam);
        param.put("content", "/api/"+System.currentTimeMillis());
        param.put("errorLog", "");
        param.put("responseTime", (50+(int)(Math.random()*50))+"");
        param.put("time", System.currentTimeMillis()+"");
        List<Object> l1 = new ArrayList<Object>();
        l1.add(param);
        String p1 = gson.toJson(l1);
        String rs = HttpRequest.post(weChatRz)
                .header("token", TimedTask.getSqDataBean().result)
                .header("Content-type", "application/json")
                .body(p1)
                .execute()
                .body();
        System.out.println("日志提交返回--->"+rs);
        return "提交成功";
    }


    @RequestMapping("spTs")
    @ResponseBody
    public String spTs(Data data) {
        Gson gson = new Gson();
        System.out.println("审批推送图文信息--------------》");
        System.out.println("Jsondata------>>>>>"+gson.toJson(data));
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("data", gson.toJson(data));
        paramMap.put("token", TimedTask.getTokenBean().getData().getToken());
        paramMap.put("appId", "0000021");
        String mapStr = gson.toJson(paramMap);
        System.out.println("原请求参数map："+paramMap);
        System.out.println("请求参数mapStr："+mapStr);
        String url = URL.spTs;
        System.out.println("url----->"+url);
        System.out.println("---post1---");
        String result1 = HttpRequest.post(url).form(paramMap).execute().body();
        System.out.println("日志提交返回--->"+result1);

        return result1;
    }

}
